import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';

import 'PicturePage.dart';

class PictureListPage extends StatefulWidget {
  PictureListPage({super.key});

  final List<PicBean> pics = [
    PicBean("assets/images/1.png", 0),
    PicBean("assets/images/2.jpeg", 0),
    PicBean("assets/images/3.jpeg", 0),
    PicBean("assets/images/4.jpg", 0),
    PicBean("assets/images/6.jpg", 0),
    PicBean("assets/images/1.png", 0),
    PicBean("assets/images/2.jpeg", 0),
    PicBean("assets/images/3.jpeg", 0),
    PicBean("assets/images/4.jpg", 0),
    PicBean("assets/images/6.jpg", 0),
    PicBean("assets/images/1.png", 0),
    PicBean("assets/images/2.jpeg", 0),
    PicBean("assets/images/3.jpeg", 0),
    PicBean("assets/images/4.jpg", 0),
    PicBean("assets/images/6.jpg", 0),
  ];

  @override
  State<PictureListPage> createState() => _PictureListPageState();
}

class _PictureListPageState extends State<PictureListPage> {
  @override
  Widget build(BuildContext context) {
    var pics = widget.pics;
    return Scaffold(
      appBar: AppBar(
        title: const Text("daex_texture"),
      ),
      body: ListView.builder(
        itemCount: pics.length,
        itemBuilder: (context, index) {
          PicBean picBean = pics[index];
          return getTextureBody(context, picBean);
        },
      ),
    );
  }

  Widget getTextureBody(BuildContext context, PicBean picBean) {
    if (picBean.id == 0) {
      return Text("Loading $picBean");
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 300,
          height: 300,
          child: Texture(textureId: picBean.id),
        ),
        Container(
          height: 10,
        ),
      ],
    );
  }

  @override
  void initState() {
    _initPictures();
    super.initState();
  }

  _initPictures() async {
    for (PicBean pic in widget.pics) {
      int id = await registerTexture(pic.name);
      pic.id = id;
      await Future.delayed(const Duration(microseconds: 200));
      setState(() {
      });
    }
  }

  @override
  void dispose() {
    for (PicBean pic in widget.pics) {
      unregisterTexture(pic.id);
    }
    super.dispose();
  }
}
